/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.teach.web;

import com.thinkgem.jeesite.common.ConstantEnum;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.ReturnObject;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.ExcelController;
import com.thinkgem.jeesite.modules.act.entity.Act;
import com.thinkgem.jeesite.modules.act.utils.ActUtils;
import com.thinkgem.jeesite.modules.sys.security.FormAuthenticationFilter;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.teach.entity.TpTeachAchievement;
import com.thinkgem.jeesite.modules.teach.service.TpTeachAchievementService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 教学成果的增删改查Controller
 *
 * @author 康力
 * @version 2018-03-11
 */
@Controller
@RequestMapping(value = "${adminPath}/teach/tpTeachAchievement")
public class TpTeachAchievementController extends ExcelController<TpTeachAchievement> {

	@Autowired
	private TpTeachAchievementService tpTeachAchievementService;
	
	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public TpTeachAchievement get(@RequestParam(required=false) String id) {
		TpTeachAchievement entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tpTeachAchievementService.get(id);
		}
		if (entity == null){
			entity = new TpTeachAchievement();
		}
		// 获得拥有当前菜单角色的最大的数据范围
		entity.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachAchievement:view"));
		System.out.println(entity.toString());
		if (entity.getIsNewRecord() && entity.getUserDataScope() == 0) {// 个人数据权限，获取个人信息
			entity.setUser(UserUtils.getUser());// 设置人员
			if (entity.getUser() != null) {
				entity.setDepartment(entity.getUser().getOffice());// 设置科室
				if (entity.getDepartment() != null) {
					// 设置教研室
					entity.setTrc(systemService.findParentByOfficeId(entity.getDepartment().getId()));
				}
			}
		}
		return entity;
	}
	/**
	 * 获得拥有当前菜单角色的最大的数据范围
	 * 0=个人数据权限   1=所在部门及以下的数据管理权限
	 * @param entity
	 * @param model
	 * @return
	 */
	/*@ModelAttribute
	public TpTeachAchievement getDataScope(TpTeachAchievement entity,Model model){
		model.addAttribute("dataScope", entity.getUserDataScope());
		return entity;
	}*/
	@RequiresPermissions("teach:tpTeachAchievement:view")
	@RequestMapping(value = {"list", ""})
	public String list(TpTeachAchievement tpTeachAchievement, HttpServletRequest request, HttpServletResponse response, Model model) {
		String str = request.getRequestURI().replaceFirst(request.getContextPath()+Global.getConfig("adminPath"), "");
		model.addAttribute("remark",systemService.getRemark(str));
		//根据拥有当前菜单角色的最大的数据范围 判断是否是获取本人数据
		tpTeachAchievement.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachAchievement:view"));
		if(tpTeachAchievement.getUserDataScope() == 0){
			tpTeachAchievement.setUser(UserUtils.getUser());
		}else{//获得当前登录人部门下的数据
			if(tpTeachAchievement.getDepartment() == null)tpTeachAchievement.setDepartment(UserUtils.getUser().getOffice());
		}
		Page<TpTeachAchievement> page = tpTeachAchievementService.findPage(new Page<TpTeachAchievement>(request, response), tpTeachAchievement); 
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			rtobj.setData(page);
			return renderString(response, rtobj);
		}
		model.addAttribute("page", page);
		return "modules/teach/tpTeachAchievementList";
	}
	@RequiresPermissions("teach:tpTeachAchievement:view")
	@RequestMapping(value = "form")
	public String form(TpTeachAchievement tpTeachAchievement, Model model, HttpServletRequest request, HttpServletResponse response) {
		//如果为新增数据并且数据权限为个人数据的情况下，启动审批流程
		String viewName = "";
		if(tpTeachAchievement == null ||
				(tpTeachAchievement.getStatus()!= null && tpTeachAchievement.getStatus() == 2)|| 
				(StringUtils.isBlank(tpTeachAchievement.getId())&&StringUtils.isBlank(tpTeachAchievement.getAct().getProcInsId()))){
			//根据流程名称获取最新的流程实例名称
			String procDefId = null;
			if(systemService.getCurUserDataScopeByPermission("teach:tpTeachAchievement:view") == 0){
				procDefId = systemService.getprocDefIdByProcDefKey(ActUtils.TP_TEACH_ACHIEVEMENT[0]);
			}
			Act act = new Act();
			act.setProcDefId(procDefId);
			tpTeachAchievement.setAct(act);
			viewName="tpTeachAchievementForm";
		} else if (tpTeachAchievement.getAct() != null && tpTeachAchievement.getAct().getTaskDefKey() != null
				&& tpTeachAchievement.getAct().getTaskDefKey().startsWith("audit")
				&&tpTeachAchievement.getAct().isTodoTask()) {
			viewName="tpTeachAchievementAudit";
		}else{
			viewName="tpTeachAchievementView";
			//如果实体类内容未查出，使用ProcInsId查询
			Act act = tpTeachAchievement.getAct();
			if(StringUtils.isBlank(tpTeachAchievement.getId()) && act != null 
					&& StringUtils.isNotBlank(act.getProcInsId())){
				tpTeachAchievement.setProcInsId(act.getProcInsId());
				List<TpTeachAchievement> list = tpTeachAchievementService.findList(tpTeachAchievement);
				if(list.size() == 1){
					tpTeachAchievement = list.get(0);
					tpTeachAchievement.setAct(act);
				}
			}
		}
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			ExportExcel ex = new ExportExcel("教学成果", TpTeachAchievement.class);
			tpTeachAchievement = ex.getMobileDataList(tpTeachAchievement);
			tpTeachAchievement.setPropertyNameMap(ex.getPropertyNameMap());
			rtobj.setData(tpTeachAchievement);
			return renderString(response, rtobj);
		}
		System.out.println(tpTeachAchievement);
		model.addAttribute("tpTeachAchievement", tpTeachAchievement);
		return "modules/teach/"+viewName;
	}

    @RequiresPermissions("teach:tpTeachAchievement:edit")
    @RequestMapping(value = "save")
    public String save(TpTeachAchievement tpTeachAchievement, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) {
        if (!beanValidator(model, tpTeachAchievement)) {
            return form(tpTeachAchievement, model, request, response);
        }
        tpTeachAchievementService.save(tpTeachAchievement);
        addMessage(redirectAttributes, "保存教学成果成功");
        return "redirect:" + Global.getAdminPath() + "/teach/tpTeachAchievement/?repage";
    }

    @RequiresPermissions("teach:tpTeachAchievement:edit")
    @RequestMapping(value = "delete")
    public String delete(TpTeachAchievement tpTeachAchievement, RedirectAttributes redirectAttributes) {
        tpTeachAchievementService.delete(tpTeachAchievement);
        addMessage(redirectAttributes, "删除教学成果成功");
        return "redirect:" + Global.getAdminPath() + "/teach/tpTeachAchievement/?repage";
    }

    @Override
    public String getTitle() {
        return "教学成果";
    }

    @Override
    public String defaultStr() {
        return "/teach/tpTeachAchievement/list";
    }

    @Override
    public CrudService baseService() {
        return tpTeachAchievementService;
    }

    @Override
    @RequiresPermissions("teach:tpTeachAchievement:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes, TpTeachAchievement t) {
        return super.importFileTemplate(response, redirectAttributes, t);
    }

    @Override
    @RequiresPermissions("teach:tpTeachAchievement:view")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes, TpTeachAchievement data) {
        return super.importFile(file, redirectAttributes, data);
    }

    @Override
    @RequiresPermissions("teach:tpTeachAchievement:view")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(TpTeachAchievement t, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        return super.exportFile(t, request, response, redirectAttributes);
    }

    @Override
    protected TpTeachAchievementService getService() {
        return tpTeachAchievementService;
    }
}